package com.aviation.air1.service.impl;



import com.aviation.air1.entity.AirportAircraftCountVO;
import com.aviation.air1.entity.AviationEntity;
import com.aviation.air1.entity.CountEntity;
import com.aviation.air1.entity.SearchConditionEntity;
import com.aviation.air1.mapper.IAviationDao1;
import com.aviation.air1.service.IAviationService1;
import com.aviation.types.Response;
import com.aviation.types.ResponseCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.*;

/**
 * @Author: dsf
 * @Description:
 * @DateTime: 2025/4/22 17:04
 **/
@Service
public class AviationService1 extends ServiceImpl<IAviationDao1, AviationEntity> implements IAviationService1 {

    @Resource
    private IAviationDao1 aviationDao1;
    private static final Map<String, String> airportNameMap = new HashMap<>();
    static {
        airportNameMap.put("PEK", "北京首都国际机场");
        airportNameMap.put("KMG", "昆明长水国际机场");
        airportNameMap.put("PVG", "上海浦东国际机场");
        airportNameMap.put("CAN", "广州白云国际机场");
        airportNameMap.put("CKG", "重庆江北国际机场");
        airportNameMap.put("CTU", "成都双流国际机场");
        airportNameMap.put("SHA", "上海虹桥国际机场");
        airportNameMap.put("HGH", "杭州萧山国际机场");
        airportNameMap.put("WNZ", "温州龙湾国际机场");
        airportNameMap.put("XMN", "厦门高崎国际机场");
        airportNameMap.put("NKG", "南京禄口国际机场");
        airportNameMap.put("XIY", "西安咸阳国际机场");
        airportNameMap.put("SHE", "沈阳桃仙国际机场");
        airportNameMap.put("JHG", "西双版纳嘎洒国际机场");
        airportNameMap.put("HAK", "海口美兰国际机场");
        airportNameMap.put("SZX", "深圳宝安国际机场");
        airportNameMap.put("TYN", "太原武宿国际机场");
        airportNameMap.put("HRB", "哈尔滨太平国际机场");
        airportNameMap.put("URC", "乌鲁木齐地窝堡国际机场");
        airportNameMap.put("CGQ", "长春龙嘉国际机场");
    }

    @Override
    public Page<AviationEntity> retrieval(List<SearchConditionEntity> conditionEntities) {
        QueryWrapper<AviationEntity> wrapper = new QueryWrapper<>();

        for (SearchConditionEntity cond : conditionEntities) {
            String type = cond.getType();
            String field = camelToUnderline(cond.getField());
            Object value = cond.getValue();

            // 特殊处理时间范围查询（两个值的数组且能解析为日期）
            if (isDateRange(value)) {
                handleDateRangeCondition(wrapper, type, field, value);
            }
            // 单值查询
            else {
                handleSingleValueCondition(wrapper, type, field, value);
            }
        }
        Page<AviationEntity> page = new Page<>(1, 10);
        Page<AviationEntity> resultPage = aviationDao1.selectPage(page, wrapper);
        return resultPage;
    }

    // 判断是否是有效的时间范围
    private boolean isDateRange(Object value) {
        if (!(value instanceof Collection)) {
            return false;
        }
        ArrayList<?> values = new ArrayList<>((Collection<?>) value);
        if (values.size() != 2) {
            return false;
        }
        return true;
    }

    // 处理时间范围条件（使用日期类型参数）
    private void handleDateRangeCondition(QueryWrapper<AviationEntity> wrapper, String type,
                                          String field, Object value) {
        ArrayList<?> values = new ArrayList<>((Collection<?>) value);
        try {
            Instant start = Instant.parse(values.get(0).toString());
            Instant end = Instant.parse(values.get(1).toString());
            switch (type) {
                case "AND":
                    wrapper.between(field, start, end);
                    break;
                case "OR":
                    wrapper.or(w -> w.between(field, start, end));
                    break;
                case "NOT":
                    wrapper.notBetween(field, start, end);
                    break;
            }
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("Invalid date format for field: " + field);
        }
    }

    // 处理单值条件
    private void handleSingleValueCondition(QueryWrapper<AviationEntity> wrapper, String type,
                                            String field, Object value) {
        switch (type) {
            case "AND":
                wrapper.eq(field, value);
                break;
            case "OR":
                wrapper.or(w -> w.eq(field, value));
                break;
            case "NOT":
                wrapper.ne(field, value);
                break;
        }
        // 打印当前 QueryWrapper 状态
//        System.out.println("After handleSingleValueCondition: " + wrapper);
    }

    @Override
    public CountEntity countAviation() {
        Integer airlinesCount = aviationDao1.countUniqueIcao();
        Integer airTypeCount = aviationDao1.countUniqueCraftType();
        Double failureRate = aviationDao1.getFailureRate();
        Integer registrationCount = aviationDao1.countUniqueRegistrationCount();
        Double memoryOccupancy = aviationDao1.caclulateMemoryOccupancy();
        Double cpuOccupancy = aviationDao1.caclulateCPUOccupancy();

        return CountEntity.builder()
                .airlinesCount(airlinesCount)
                .airTypeCount(airTypeCount)
                .registrationCount(registrationCount)
                .memoryOccupancy(memoryOccupancy)
                .failureRate(failureRate)
                .CPUOccupancy(cpuOccupancy)
                .build();
    }

    @Override
    public List<AirportAircraftCountVO> getAircraftCountByAirport() {
        List<AirportAircraftCountVO> list = aviationDao1.countAircraftByAirport();
        for (AirportAircraftCountVO vo : list) {
            vo.setAirportName(airportNameMap.getOrDefault(vo.getAirport(), "未知机场"));
        }
        return list;
    }


    private String camelToUnderline(String str) {
        if (str == null || str.isEmpty()) return str;
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (Character.isUpperCase(c)) {
                result.append("_").append(Character.toLowerCase(c));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }
}
